package com.jichangxiu.framework.provider;

import cn.hutool.core.util.ObjectUtil;
import com.jichangxiu.common.constant.Constants;
import com.jichangxiu.common.entity.bo.DataSource;
import com.jichangxiu.common.properties.DruidProperties;
import com.jichangxiu.framework.factory.DynamicFactory;
import com.jichangxiu.framework.service.DynamicService;
import com.jichangxiu.framework.utils.DynamicUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Component
public class DynamicProvider implements ApplicationListener<ContextRefreshedEvent> {

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    private final DynamicService dynamicService = DynamicFactory.dynamicService();

    private DruidProperties druidProperties;

    @Autowired
    public void setDruidProperties(DruidProperties druidProperties) {
        this.druidProperties = druidProperties;
    }

    // 初始化本平台的数据源
    @PostConstruct
    public void init() throws Exception {
        DynamicUtils.addDataSource(druidProperties, Constants.DEFAULT_DATA_SOURCE, url, username, password);
        DynamicUtils.changeSource(Constants.DEFAULT_DATA_SOURCE);
    }

    // 查询本平台数据库中配置的链接信息
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        List<DataSource> dataSourceList = dynamicService.sourceList();
        if (ObjectUtil.isNotEmpty(dataSourceList)) {
            dataSourceList.forEach(dataSource -> {
                try {
                    DynamicUtils.addDataSource(druidProperties, dataSource);
                } catch (Exception ex) {
                    log.error("【DynamicProvider】添加数据源【" + dataSource.getCode() + "】失败");
                }
            });
        }
    }

}
